package in.muton.edushare.poll.pages;

import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.poll.panels.PollList;
import in.muton.edushare.poll.sections.PollRespondPanel;
import in.muton.edushare.url.URLLoader;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.List;

import org.apache.wicket.PageParameters;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.markup.html.CSSPackageResource;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.constants.URLConstants;
import com.edushare.common.dao.PollsDAO;
import com.edushare.common.dao.UserPollDAO;
import com.edushare.common.vo.Poll;
import com.edushare.common.vo.UserPoll;
import com.edushare.common.vo.Users;

public class PollAnswer extends EduShareBasePage {

	public PollAnswer(PageParameters params) {
		add(CSSPackageResource
				.getHeaderContribution(PollList.class, "Poll.css"));
		Poll p = new PollsDAO(getSessionORMInterface()).getPollById(Integer
				.parseInt(params.getString("0")));
		UserPollDAO upDAO = new UserPollDAO(getSessionORMInterface());
		List<Users> respList = upDAO.getPollRespondents(p);
		List<Users> reviewList = upDAO.getPollObservers(p);

		if (respList.contains(getLoggedInUser())) {
			preview = false;
		} else if (reviewList.contains(getLoggedInUser())) {
			preview = true;
		} else if (p.getCreator() == getLoggedInUser()) {
			preview = true;
		} else {
			throw new RestartResponseException(URLLoader
					.getPageClass(URLConstants.UNAUTHORIZED_PATH));
		}
		pollModel = new CayenneModel<Poll>(p);
		if(preview){
			setErrorMessage("You are not a poll participant. This poll is being shown " +
					"to you in preview mode. Your responses will not be saved");
		}else if (new UserPollDAO(getSessionORMInterface()).getPollStatus(
				getLoggedInUser(), p) == UserPoll.POLL_COMPLETE) {
			setErrorMessage("You have already completed this survey."
					+ "If you submit again, your earlier responses will be overwritten");
		}
		add(new PollRespondPanel("pollRespondPanel", pollModel, this, preview));
	}

	@Override
	public String getPageTitle() {
		return getLoggedInUser().getCompleteUserName() + " | Poll | "
				+ ApplicationConstants.APPLICATION_NAME;
	}

	@Override
	public String getUserRole() {
		return "";
	}

	private CayenneModel<Poll> pollModel;
	private boolean preview = false;
	public static final String anonymousString = "This survey is anonymous, your identity and personal details will not be stored"
			+ "with your respones.";
	public static final String nonAnonString = "This survey is not anonymous, your identity will be stored in addition to your responses.";
	public static final String publicString = "The results of this survey are public. After you are done with the survey, you will be able to view others' responses.";
	public static final String nonPublicString = "";
}
